import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { Card, Row, Col, Statistic, Table, Button, Space, message, Spin, Progress, Tag } from 'antd';
import { ReloadOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import api from '../services/api';
import ResizableTable from '../components/ResizableTable';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

interface PortfolioDetail {
  id: number;
  name: string;
  user: number;
  total_amount: number;
  current_value: number;
  target_allocation: {
    stable: number;
    balanced: number;
    growth: number;
    aggressive: number;
  };
  created_at: string;
  updated_at: string;
}

interface Holding {
  id: number;
  product: {
    id: number;
    code: string;
    name: string;
    category: {
      name: string;
      code: string;
    };
    product_type: string;
    risk_level: number;
  };
  shares: number;
  cost_price: number;
  current_price: number;
  cost_amount: number;
  current_amount: number;
  purchase_date: string;
  profit_loss: number;
  profit_loss_rate: number;
}

interface Transaction {
  id: number;
  transaction_type: string;
  product: {
    code: string;
    name: string;
  };
  shares: number;
  price: number;
  amount: number;
  transaction_date: string;
  status: string;
}

const PortfolioDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [portfolio, setPortfolio] = useState<PortfolioDetail | null>(null);
  const [holdings, setHoldings] = useState<Holding[]>([]);
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [loading, setLoading] = useState(true);

  const holdingColumns: ColumnsType<Holding> = [
    {
      title: '产品代码',
      dataIndex: ['product', 'code'],
      key: 'code',
      width: 120,
    },
    {
      title: '产品名称',
      dataIndex: ['product', 'name'],
      key: 'name',
      width: 200,
    },
    {
      title: '产品类型',
      dataIndex: ['product', 'product_type'],
      key: 'product_type',
      width: 100,
      render: (type: string) => {
        const typeMap: { [key: string]: { text: string; color: string } } = {
          'stable': { text: '稳健型', color: 'green' },
          'balanced': { text: '平衡型', color: 'blue' },
          'growth': { text: '成长型', color: 'orange' },
          'aggressive': { text: '进取型', color: 'red' },
        };
        const config = typeMap[type] || { text: type, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '持有份额',
      dataIndex: 'shares',
      key: 'shares',
      width: 120,
      render: (value: number) => value?.toFixed(2) || '-',
    },
    {
      title: '成本价',
      dataIndex: 'cost_price',
      key: 'cost_price',
      width: 100,
      render: (value: number) => `¥${value?.toFixed(4) || '-'}`,
    },
    {
      title: '现价',
      dataIndex: 'current_price',
      key: 'current_price',
      width: 100,
      render: (value: number) => `¥${value?.toFixed(4) || '-'}`,
    },
    {
      title: '成本金额',
      dataIndex: 'cost_amount',
      key: 'cost_amount',
      width: 120,
      render: (value: number) => `¥${value?.toFixed(2) || '-'}`,
    },
    {
      title: '市值',
      dataIndex: 'current_amount',
      key: 'current_amount',
      width: 120,
      render: (value: number) => `¥${value?.toFixed(2) || '-'}`,
    },
    {
      title: '盈亏',
      dataIndex: 'profit_loss',
      key: 'profit_loss',
      width: 120,
      render: (value: number) => {
        const color = value > 0 ? '#3f8600' : value < 0 ? '#cf1322' : '#666';
        return <span style={{ color }}>{value > 0 ? '+' : ''}¥{value?.toFixed(2) || '-'}</span>;
      },
    },
    {
      title: '盈亏率',
      dataIndex: 'profit_loss_rate',
      key: 'profit_loss_rate',
      width: 100,
      render: (value: number) => {
        const color = value > 0 ? '#3f8600' : value < 0 ? '#cf1322' : '#666';
        return <span style={{ color }}>{value > 0 ? '+' : ''}{(value * 100)?.toFixed(2) || '-'}%</span>;
      },
    },
  ];

  const transactionColumns: ColumnsType<Transaction> = [
    {
      title: '交易日期',
      dataIndex: 'transaction_date',
      key: 'transaction_date',
      width: 120,
      render: (value: string) => dayjs(value).format('YYYY-MM-DD'),
    },
    {
      title: '交易类型',
      dataIndex: 'transaction_type',
      key: 'transaction_type',
      width: 100,
      render: (type: string) => {
        const typeMap: { [key: string]: { text: string; color: string } } = {
          'buy': { text: '买入', color: 'green' },
          'sell': { text: '卖出', color: 'red' },
          'dividend': { text: '分红', color: 'blue' },
        };
        const config = typeMap[type] || { text: type, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '产品代码',
      dataIndex: ['product', 'code'],
      key: 'product_code',
      width: 120,
    },
    {
      title: '产品名称',
      dataIndex: ['product', 'name'],
      key: 'product_name',
      width: 200,
    },
    {
      title: '份额',
      dataIndex: 'shares',
      key: 'shares',
      width: 120,
      render: (value: number) => value?.toFixed(2) || '-',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render: (value: number) => `¥${value?.toFixed(4) || '-'}`,
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (value: number) => `¥${value?.toFixed(2) || '-'}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap: { [key: string]: { text: string; color: string } } = {
          'completed': { text: '已完成', color: 'green' },
          'pending': { text: '待处理', color: 'orange' },
          'cancelled': { text: '已取消', color: 'red' },
        };
        const config = statusMap[status] || { text: status, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
  ];

  const fetchPortfolioDetail = async () => {
    if (!id) return;
    
    setLoading(true);
    try {
      // 获取投资组合详情
      const portfolioResponse = await api.get(`/api/portfolios/${id}/`);
      setPortfolio(portfolioResponse.data);

      // 获取持仓信息
      const holdingsResponse = await api.get(`/api/portfolios/${id}/holdings/`);
      setHoldings(holdingsResponse.data.results || holdingsResponse.data);

      // 获取交易记录
      const transactionsResponse = await api.get(`/api/portfolios/${id}/transactions/`);
      setTransactions(transactionsResponse.data.results || transactionsResponse.data);
    } catch (error) {
      message.error('获取投资组合详情失败');
      console.error('Error fetching portfolio detail:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleRefresh = () => {
    fetchPortfolioDetail();
  };

  const handleEdit = () => {
    message.info('编辑功能开发中...');
  };

  const handleAddTransaction = () => {
    message.info('添加交易功能开发中...');
  };

  useEffect(() => {
    fetchPortfolioDetail();
  }, [id]);

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!portfolio) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <p>未找到投资组合信息</p>
      </div>
    );
  }

  const totalProfitLoss = portfolio.current_value - portfolio.total_amount;
  const totalProfitLossRate = portfolio.total_amount > 0 
    ? (totalProfitLoss / portfolio.total_amount) * 100 
    : 0;

  // 计算当前配置比例
  const currentAllocation = holdings.reduce((acc, holding) => {
    const type = holding.product.product_type;
    acc[type] = (acc[type] || 0) + holding.current_amount;
    return acc;
  }, {} as { [key: string]: number });

  const totalValue = portfolio.current_value;
  const currentAllocationPercent = {
    stable: totalValue > 0 ? (currentAllocation.stable || 0) / totalValue * 100 : 0,
    balanced: totalValue > 0 ? (currentAllocation.balanced || 0) / totalValue * 100 : 0,
    growth: totalValue > 0 ? (currentAllocation.growth || 0) / totalValue * 100 : 0,
    aggressive: totalValue > 0 ? (currentAllocation.aggressive || 0) / totalValue * 100 : 0,
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card 
        title={portfolio.name}
        extra={
          <Space>
            <Button 
              icon={<ReloadOutlined />} 
              onClick={handleRefresh}
              loading={loading}
            >
              刷新
            </Button>
            <Button 
              icon={<EditOutlined />} 
              onClick={handleEdit}
            >
              编辑
            </Button>
            <Button 
              type="primary"
              icon={<PlusOutlined />} 
              onClick={handleAddTransaction}
            >
              添加交易
            </Button>
          </Space>
        }
        style={{ marginBottom: '24px' }}
      >
        <Row gutter={[24, 16]}>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="总资产"
              value={portfolio.current_value}
              precision={2}
              prefix="¥"
              valueStyle={{ fontSize: '24px' }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="总成本"
              value={portfolio.total_amount}
              precision={2}
              prefix="¥"
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="总盈亏"
              value={totalProfitLoss}
              precision={2}
              prefix="¥"
              valueStyle={{ 
                color: totalProfitLoss > 0 ? '#3f8600' : totalProfitLoss < 0 ? '#cf1322' : '#666'
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Statistic
              title="总收益率"
              value={totalProfitLossRate}
              precision={2}
              suffix="%"
              valueStyle={{ 
                color: totalProfitLossRate > 0 ? '#3f8600' : totalProfitLossRate < 0 ? '#cf1322' : '#666'
              }}
            />
          </Col>
        </Row>
      </Card>

      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} lg={12}>
          <Card title="资产配置" style={{ height: '300px' }}>
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <h4>目标配置</h4>
                <div style={{ marginBottom: '8px' }}>
                  <span>稳健型: {portfolio.target_allocation.stable}%</span>
                  <Progress percent={portfolio.target_allocation.stable} size="small" />
                </div>
                <div style={{ marginBottom: '8px' }}>
                  <span>平衡型: {portfolio.target_allocation.balanced}%</span>
                  <Progress percent={portfolio.target_allocation.balanced} size="small" />
                </div>
                <div style={{ marginBottom: '8px' }}>
                  <span>成长型: {portfolio.target_allocation.growth}%</span>
                  <Progress percent={portfolio.target_allocation.growth} size="small" />
                </div>
                <div style={{ marginBottom: '8px' }}>
                  <span>进取型: {portfolio.target_allocation.aggressive}%</span>
                  <Progress percent={portfolio.target_allocation.aggressive} size="small" />
                </div>
              </Col>
              <Col span={12}>
                <h4>当前配置</h4>
                <div style={{ marginBottom: '8px' }}>
                  <span>稳健型: {currentAllocationPercent.stable.toFixed(1)}%</span>
                  <Progress percent={currentAllocationPercent.stable} size="small" />
                </div>
                <div style={{ marginBottom: '8px' }}>
                  <span>平衡型: {currentAllocationPercent.balanced.toFixed(1)}%</span>
                  <Progress percent={currentAllocationPercent.balanced} size="small" />
                </div>
                <div style={{ marginBottom: '8px' }}>
                  <span>成长型: {currentAllocationPercent.growth.toFixed(1)}%</span>
                  <Progress percent={currentAllocationPercent.growth} size="small" />
                </div>
                <div style={{ marginBottom: '8px' }}>
                  <span>进取型: {currentAllocationPercent.aggressive.toFixed(1)}%</span>
                  <Progress percent={currentAllocationPercent.aggressive} size="small" />
                </div>
              </Col>
            </Row>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="组合信息" style={{ height: '300px' }}>
            <p><strong>创建时间：</strong>{dayjs(portfolio.created_at).format('YYYY-MM-DD HH:mm:ss')}</p>
            <p><strong>更新时间：</strong>{dayjs(portfolio.updated_at).format('YYYY-MM-DD HH:mm:ss')}</p>
            <p><strong>持仓数量：</strong>{holdings.length}个</p>
            <p><strong>交易记录：</strong>{transactions.length}笔</p>
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col span={24}>
          <Card title="持仓明细" style={{ marginBottom: '24px' }}>
            <ResizableTable
              columns={holdingColumns}
              dataSource={holdings}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              scroll={{ x: 1200 }}
            />
          </Card>
        </Col>
        <Col span={24}>
          <Card title="交易记录">
            <ResizableTable
              columns={transactionColumns}
              dataSource={transactions}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              scroll={{ x: 1000 }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default PortfolioDetail;